<template>
  <div class="card">
    <h3>仓库</h3>
    <form @submit.prevent="create">
      <input v-model="form.name" placeholder="名称" required />
      <input v-model="form.location" placeholder="位置" required />
      <input v-model.number="form.capacity" placeholder="容量" type="number" min="0" required />
      <button type="submit">新增</button>
    </form>
    <table>
      <thead>
        <tr><th>ID</th><th>名称</th><th>位置</th><th>容量</th><th></th></tr>
      </thead>
      <tbody>
        <tr v-for="w in list" :key="w.id">
          <td>{{ w.id }}</td>
          <td><input v-model="w.name"/></td>
          <td><input v-model="w.location"/></td>
          <td><input v-model.number="w.capacity" type="number" min="0"/></td>
          <td>
            <button @click="update(w)">保存</button>
            <button @click="remove(w.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { api, type Warehouse } from '../lib/api'

const list = ref<Warehouse[]>([])
const form = reactive({ name: '', location: '', capacity: 0 })

async function load() {
  const { data } = await api.get<Warehouse[]>('/warehouses')
  list.value = data
}

async function create() {
  await api.post('/warehouses', form)
  form.name = ''; form.location=''; form.capacity=0
  await load()
}

async function update(w: Warehouse) { await api.put(`/warehouses/${w.id}`, w); await load() }
async function remove(id: number) { await api.delete(`/warehouses/${id}`); await load() }

onMounted(load)
</script>


